package com.lw.extraceim.ui.activity.customer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;

import com.google.gson.reflect.TypeToken;
import com.lw.extraceim.R;
import com.lw.extraceim.loader.CustomerLoader;
import com.lw.extraceim.model.CustomerInfo;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.adapter.CustomerAdapter;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.view.ExtraceToolbar;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 客户列表界面
 * @Date : 2019/4/14 10:40
 */
public class CustomerListActivity extends BaseActivity {

    private static final String TAG = "CustomerListActivity";

    private SearchView mSearchView;
    private ExtraceToolbar mToolbar;
    private ListView mLvCustomerList;

    private CustomerAdapter customerAdapter;
    private List<CustomerInfo> customerInfoList;
    private int resultCode;
    private boolean isForResult;
    private String query;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_customer_list);
        mSearchView = findViewById(R.id.search_view);

        mLvCustomerList = findViewById(R.id.customer_list);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();
    }

    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomerListActivity.this.finish();
            }
        });
        mToolbar.setTitle("客户列表");
        mToolbar.setButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(customerAdapter.getVisibility() == View.VISIBLE){
                    customerAdapter.setVisibility(View.GONE);
                }else{
                    customerAdapter.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        resultCode = intent.getIntExtra("resultCode",0);
        Log.d(TAG, "initData: " + resultCode);
        isForResult = intent.getBooleanExtra("isForResult",false);

        customerAdapter = new CustomerAdapter(customerInfoList,this);
        mLvCustomerList.setAdapter(customerAdapter);
    }

    @Override
    public void refreshUI() {

    }

    @Override
    public void initEvent() {
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                CustomerListActivity.this.query = query;
                loadCustomer(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        mLvCustomerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemClick: " +  customerInfoList.get(position));
                if (isForResult){
                    Intent intent = getIntent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("customerInfo",customerInfoList.get(position));
                    intent.putExtras(bundle);
                    CustomerListActivity.this.setResult(resultCode,intent);
                    CustomerListActivity.this.finish();
                }

            }
        });
    }

    /**
     * 通过姓名查找客户信息
     * @param name
     */
    public void loadCustomer(String name) {
        final CustomerLoader customerLoader = new CustomerLoader(this);
        customerLoader.get(name, null, null, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
                Log.d(TAG, "onError: 网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    try {
                        customerInfoList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("customerList").toString(), new TypeToken<List<CustomerInfo>>() {
                        });
                        for(CustomerInfo customerInfo : customerInfoList){
                            customerInfo.onSave();
                        }
//                        mLvCustomerList.setAdapter(new CustomerAdapter(customerInfoList,CustomerListActivity.this));
                        customerAdapter.setCustomerInfoList(customerInfoList);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        alert("解析失败 ");
                    }
                } else {
                    alert("查询失败");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        switch (requestCode){
            case CustomerEditActivity.CUSTOMER_EDIT_ACTIVITY_CODE:{
               CustomerInfo customer = (CustomerInfo) data.getSerializableExtra("customerInfo");
               toast("修改成功");
               loadCustomer(query);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }


    public static void actionStartForResult(@NonNull Activity context,int resultCode){
        Intent intent = new Intent(context,CustomerListActivity.class);
        Log.d(TAG, "actionStartForResult: " + resultCode);
        intent.putExtra("resultCode",resultCode);
        intent.putExtra("isForResult",true);
        context.startActivityForResult(intent,CustomerEditActivity.CUSTOMER_EDIT_ACTIVITY_CODE);
    }
}
